package com.android.delivery.dialog;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import com.android.delivery.R;
import com.android.delivery.constant.Constants;
import com.android.delivery.entity.Addr;
import com.android.delivery.util.ToastUtils;


/**
 * Desc:导航弹框
 * <p>
 * Author: [李豫]
 * Date: 2018-08-02
 * Copyright: Copyright (c) 2010-2018
 * Updater:
 * Update Time:
 * Update Comments:
 */
public class NavigationDialog extends DialogFragment implements View.OnClickListener {

    private Addr mAddr;

    public static NavigationDialog newInstance(Addr addr) {
        NavigationDialog payMethodDialog = new NavigationDialog();
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constants.ITEM, addr);
        payMethodDialog.setArguments(bundle);
        return payMethodDialog;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(true);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.customDialog);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getDialog().setCanceledOnTouchOutside(true);
        Window window = getDialog().getWindow();
        window.getAttributes().windowAnimations = R.style.PopAnimBottom;
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View dialogView = inflater.inflate(R.layout.popup_nagivation, container, false);

        dialogView.findViewById(R.id.tv_gaode).setOnClickListener(this);
        dialogView.findViewById(R.id.tv_baidu).setOnClickListener(this);
        dialogView.findViewById(R.id.tv_tenxun).setOnClickListener(this);
        dialogView.findViewById(R.id.tv_cancel).setOnClickListener(this);

        initData();
        return dialogView;
    }

    private void initData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mAddr = bundle.getParcelable(Constants.ITEM);
        }
    }

    public void show(FragmentManager manager) {
        if (!isShowing()) {
            show(manager, NavigationDialog.class.getSimpleName());
        }
    }

    public boolean isShowing() {
        if (getDialog() != null && getDialog().isShowing()) {
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.tv_gaode) {
            navigatGaode();
            dismiss();
        } else if (viewId == R.id.tv_baidu) {
            navigatBaidu();
            dismiss();
        } else if (viewId == R.id.tv_tenxun) {
            navigatTenx();
            dismiss();
        } else if (viewId == R.id.tv_cancel) {
            dismiss();
        }
    }

    /**
     * 打开高德地图（公交出行，起点位置使用地图当前位置）
     * <p>
     * t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
     */
    private void navigatGaode() {
        if (checkMapAppsIsExist(getActivity(), "com.autonavi.minimap")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setPackage("com.autonavi.minimap");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setData(Uri.parse("androidamap://route?sourceApplication=" + R.string.app_name
                    + "&sname=我的位置&dlat=" + mAddr.latitude
                    + "&dlon=" + mAddr.longitude
                    + "&dname=" + mAddr.address
                    + "&dev=0&m=0&t=3"));
            startActivity(intent);
        } else {
            ToastUtils.showShort(getActivity(), "您尚未安装高德地图");
        }
    }

    /**
     * 打开百度地图（公交出行，起点位置使用地图当前位置）
     * <p>
     * mode = transit（公交）、driving（驾车）、walking（步行）和riding（骑行）. 默认:driving
     * 当 mode=transit 时 ： sy = 0：推荐路线 、 2：少换乘 、 3：少步行 、 4：不坐地铁 、 5：时间短 、 6：地铁优先
     */
    private void navigatBaidu() {
        if (checkMapAppsIsExist(getActivity(), "com.baidu.BaiduMap")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("baidumap://map/direction?origin=我的位置&destination=name:"
                    + mAddr.address
                    + "|latlng:" + mAddr.latitude + "," + mAddr.longitude
                    + "&mode=riding&sy=0&index=0&target=1"));
            startActivity(intent);
        } else {
            ToastUtils.showShort(getActivity(), "您尚未安装百度地图");
        }
    }

    /**
     * 打开腾讯地图（公交出行，起点位置使用地图当前位置）
     * <p>
     * 公交：type=bus，policy有以下取值
     * 0：较快捷 、 1：少换乘 、 2：少步行 、 3：不坐地铁
     * 驾车：type=drive，policy有以下取值
     * 0：较快捷 、 1：无高速 、 2：距离短
     * policy的取值缺省为0
     */
    private void navigatTenx() {
        if (checkMapAppsIsExist(getActivity(), "com.tencent.map")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("qqmap://map/routeplan?type=drive&from=我的位置&fromcoord=0,0"
                    + "&to=" + mAddr.address
                    + "&tocoord=" + mAddr.latitude + "," + mAddr.longitude
                    + "&policy=0&referer=myapp"));
            startActivity(intent);
        } else {
            ToastUtils.showShort(getActivity(), "您尚未安装腾讯地图");
        }
    }

    /**
     * 检测地图应用是否安装
     *
     * @param context
     * @param packagename
     * @return
     */
    public boolean checkMapAppsIsExist(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo != null;
    }
}

